package com.lisp.dl.classloader;

import java.io.File;

import org.apache.commons.io.FileUtils;

public class ModuleClassLoader extends ClassLoader {
	
	public static final String REPOSITORY = "target/classes";
	
	public static final String MODULE_PACKAGE = "com.lisp.dl.module.";
	
	public static final String MODULE_IMPL_PACKAGE = "com.lisp.dl.module.impl.";
	
	@Override
	public Class<?> loadClass(String clazz) throws ClassNotFoundException {
		System.out.println("initiate loading: " + clazz);
		// 如果是module实现类，自己加载
		if(isModuleImplClass(clazz)) {
			System.out.println("actually loaded: " + clazz);
			File f = new File(REPOSITORY, clazz.replace('.', File.separatorChar)+".class");
			try {
				byte[] classData = FileUtils.readFileToByteArray(f);
				return defineClass(clazz, classData, 0, classData.length);
			} catch (Exception e) {
				throw new RuntimeException("[自定义类加载器] 加载出错"); 
			}
		} else {
			// 非module实现类，交给parent classloader处理
			return getParent().loadClass(clazz);
		}
	}
	
	private boolean isModuleImplClass(String clazz) {
		return clazz.startsWith(MODULE_PACKAGE)
				// 注释掉下面这个条件就会产生ClassCastException
				&& !clazz.equals(MODULE_PACKAGE + "IModule");
	}
}
